#!/usr/bin/python

#Ganna Raboshchuk {ganna.raboshchuk@upc.edu}
#21.10.2013
#UPC, Barcelona

#Smooth the decision labels - decrease number of insertions.
#--------------------------------------------------------------------------

import sys

START_TIME = 0
END_TIME = 1
CLASS = 2

#resultsFolder = "/home/anna/Hospital/Segmentation/Alarms_detection/Code_bash/recognition/#Ch24_C24_ff_S3_G3_out_30-10_44100_reducedFB_min/S4"
#p = -10
#WINDOW = 5 #in 10ms
resultsFolder = sys.argv[1]
p = sys.argv[2]
WINDOW = int(sys.argv[3])

resultFile = resultsFolder + '/out_' + str(p) + '.mmf'
labelling = open(resultFile, 'r')

outputFile = resultsFolder + '/out_smooth_' + str(p) + '.mmf'
output = open(outputFile, 'w')
output.write('#!MLF!#\n')

smoothedLabelling = []
count = 0 #iterating inside a window
#Counters of the labels inside a window
alarms = 0
nonAlarms = 0
startTime = 0
endTime = 0

def outputLabel():
    global startTime
    global endTime
    global smoothedLabelling
    
    label = 'al' if (alarms > nonAlarms) else 'ot'
    
    for i in range((int(endTime)-int(startTime))/100000):        
        smoothedLabelling.append([str(int(startTime)+100000*i), str(int(startTime)+100000*(i+1)), label])
    startTime = endTime
 

for line in labelling:
    if not line[0].isdigit():        
        if (line != '#!MLF!#\n'):
            if (line == '.\n'):
                outputLabel()
                              
                for i in range(len(smoothedLabelling)):
                    output.write(str(smoothedLabelling[i][START_TIME]) + ' ' + str(smoothedLabelling[i][END_TIME]) \
                             + ' ' + smoothedLabelling[i][CLASS] + '\n')
                output.write('.\n')
                smoothedLabelling = []
		count = 0
		startTime = 0
            else:
                output.write(line) #output the name of the testing file
            
    else: #reading in labelling
        labels = line.split()
        endTime = labels[END_TIME]
        if labels[CLASS] == 'ot':
            nonAlarms += 1
        else:
            alarms += 1
        count += 1
        if count == WINDOW:   
            outputLabel()
            count = 0
            alarms = 0
            nonAlarms = 0                  
     
labelling.close()
output.close()
           

